package com.yc.controller;

//import org.keycloak.representations.AccessTokenResponse;

import com.alibaba.fastjson.JSONObject;
import org.keycloak.KeycloakPrincipal;
import org.keycloak.KeycloakSecurityContext;
import org.keycloak.adapters.KeycloakDeployment;
import org.keycloak.adapters.KeycloakDeploymentBuilder;
import org.keycloak.adapters.RefreshableKeycloakSecurityContext;
import org.keycloak.adapters.rotation.AdapterTokenVerifier;
import org.keycloak.adapters.spi.KeycloakAccount;
import org.keycloak.representations.AccessToken;
import org.keycloak.representations.adapters.config.AdapterConfig;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.Principal;
import java.util.Map;

/**
 * @author yangc91
 * @date 2020/8/22 15:06
 */
@RestController
public class LoginController {
    @PostMapping("/login")
    public Object getToken(@RequestBody Map<String, String> credentials) {
//        Keycloak kc = Keycloak.getInstance("http://localhost:8080/auth",
//                 credentials.get("company"),
//                 credentials.get("username"),
//                credentials.get("password"),
//                credentials.get("clientId"));
//
//        return kc.tokenManager().getAccessToken();
        return null;

    }

    @GetMapping(path = "/")
    public String index() {
        return "external";
    }

    @GetMapping(path = "/customer")
    public String customers(HttpServletRequest request) {
        RefreshableKeycloakSecurityContext keycloak = (RefreshableKeycloakSecurityContext) request.getAttribute(KeycloakSecurityContext.class.getName());


        return "customer :: " + keycloak.getTokenString()+"\n"+ JSONObject.toJSONString(keycloak);
    }

    @GetMapping(path = "/admin")
    public String admin(HttpServletRequest request) {
        KeycloakSecurityContext keycloak = (KeycloakSecurityContext) request.getAttribute(KeycloakSecurityContext.class.getName());
        return "admin :: " + keycloak.getTokenString();
    }
    @GetMapping(path = "/loginout")
    public String loginout(HttpServletRequest request, HttpServletResponse response) {
        KeycloakSecurityContext keycloak = (KeycloakSecurityContext) request.getAttribute(KeycloakSecurityContext.class.getName());
        try {
            response.addHeader("Access-Control-Allow-Origin", "*");
            request.logout();
        } catch (ServletException e) {
            e.printStackTrace();
        }
        return "loginout :: ";
    }
    @GetMapping("/vaild")
    public boolean vaild(HttpServletRequest request) {
        AccessToken accessToken = null;
        RefreshableKeycloakSecurityContext keycloak = (RefreshableKeycloakSecurityContext) request.getAttribute(KeycloakSecurityContext.class.getName());
        try {
            AccessToken token = keycloak.getToken();
            KeycloakDeployment deployment = keycloak.getDeployment();
            //1、设置client配置信息
            AdapterConfig adapterConfig = new AdapterConfig();
            //realm name
            adapterConfig.setRealm(deployment.getRealm());
            //client_id
            adapterConfig.setResource(token.getIssuedFor());
            //认证中心keycloak地址
            adapterConfig.setAuthServerUrl(keycloak.getTokenString());
            //访问https接口时，禁用证书检查。
            adapterConfig.setDisableTrustManager(true);
            //2、根据client配置信息构建KeycloakDeployment对象
            KeycloakDeployment deployment1 = KeycloakDeploymentBuilder.build(adapterConfig);
            //3、执行token签名验证和有效性检查（不通过会抛异常）
            accessToken = AdapterTokenVerifier.verifyToken(keycloak.getTokenString(), deployment1);
        }catch (Exception e){
            e.printStackTrace();
        }
        if(accessToken!=null){
            return true;
        }else{
            return false;
        }
    }
}
